// axios 封装 为了  配置基础路径，超时时间等其他基本信息
// 引入
import type {
  AxiosError,
  AxiosInstance,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from 'axios'
import axios from 'axios'
// const baseURL = ''
const baseURL = 'http://localhost:8000'
// 创建实例
const request: AxiosInstance = axios.create({
  baseURL,
  timeout: 1000 * 60 * 20,
})

// 添加请求和响应拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // config 配置对象，headers属性请求头
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error.message)
  },
)

declare module 'axios' {
  interface AxiosResponse<T = any> {
    success: boolean
    message?: string
    data: T
  }
}
// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    response.message = response.data.message || response.data.error || void 0
    // 失败的回调
    if (response.status !== 200) {
      response.success = false
      return Promise.reject(response)
    }
    response.success = true
    return Promise.resolve(response)
  },
  (error) => {
    console.warn('error', error)
    const response = error?.response
    // 失败的回调。一般处理网络错误
    const codeMessage: Record<number, string> = {
      400: 'Bad Request',
      401: 'Token Expired',
      403: 'Forbidden',
      404: 'Not Found',
      500: 'Internal Server Error',
      502: 'Bad Gateway',
      503: 'Service Unavailable',
      504: 'Gateway Timeout',
    }

    const status = response?.status
    let msg = 'Unknown error,please try again later'

    if (status) {
      msg = response?.data?.message || response?.data?.error || codeMessage[status] || '错误'
    }
    else if (error.message.includes('timeout')) {
      msg = 'timeout'
    }
    else if (error.message.includes('Network Error')) {
      msg = 'Network Error'
    }
    error.message = msg
    error.success = false
    return Promise.reject(error)
  },
)
export default request
